<template>
  <div class="admin-login">
    <h2>登录</h2>
    <el-form :model="userInfo" :rules="userRules" ref="loginForm">
      <div class="input-group">
        <el-form-item prop="username"
          ><el-input
            v-model="userInfo.username"
            placeholder="请输入账号"
          ></el-input
        ></el-form-item>
      </div>
      <div class="input-group">
        <el-form-item prop="password">
          <el-input
            v-model="userInfo.password"
            placeholder="请输入密码"
            type="password"
          ></el-input>
        </el-form-item>
      </div>
      <div class="input-group">
        <el-button class="login-btn" @click="submitLogin('loginForm')"
          >登录</el-button
        >
      </div>
    </el-form>
  </div>
</template>

<script>
import { mapActions } from "vuex";

export default {
  name: "LoginView",
  data() {
    // 自定义校验
    const validateUser = (rule, value, callback) => {
      const pat = /^\w{3,8}$/i;
      if (pat.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的账号"));
      }
    };
    return {
      userInfo: {
        username: "",
        password: "",
      },
      userRules: {
        username: [
          { required: true, message: "请输入帐号", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" },
          { validator: validateUser, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    // ...mapActions(["loginAction"]), // store子模块没有加命名空间
    ...mapActions(["userStore/loginAction"]), // store子模块加了命名空间
    submitLogin(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 登录
          this["userStore/loginAction"]({
            userId: 1,
            token: "bkchbsj",
            username: this.userInfo.username,
          }).then(() => {
            this.$router.push("/");
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../assets/scss/var";

.admin-login {
  width: 300px;
  padding: 15px;
  box-shadow: 0 0 3px #ddd;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #fff;

  h2 {
    text-align: center;
  }

  .input-group {
    margin-top: 15px;

    .login-btn {
      width: 100%;
      background: $theme-color;
      color: #fff;
    }
  }
}
</style>